package com.sprucetec.live.watcher;

import com.sprucetec.live.cache.JvmCache;
import com.sprucetec.live.constants.RedisKeyConstant;
import com.sprucetec.live.constants.ZkCacheConstant;
import com.sprucetec.live.enums.WatchTypeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName ZookeeperWatcher
 * @Description: zk 同步jvm级别缓存
 * @Author Kenny
 * @Date 2020/4/26
 **/

@Component
@Slf4j
@Data
public class ZookeeperWatcher implements Watcher {

    public static ZooKeeper zooKeeper;

    public static RedisTemplate redisTemplate;

    @Override
    public void process(WatchedEvent watchedEvent) {

        System.out.println("get notification.");

        if (watchedEvent.getType() == Event.EventType.None && watchedEvent.getPath() == null) {
            createVideoDetailNode();
            createIntranetIpNode();

        } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            try {
                // 获取节点路径
                String path = watchedEvent.getPath();
                // 获取节点数据
                String data = new String(zooKeeper.getData(path, true, new Stat()));
                // 处理当前服务器对应 JVM 缓存
                log.info("缓存更新监听触发=》" + path);
                refreshVideoDetailCache(data, path);// 更新视频缓存
                refreshIntranetIp(data); // 更新内网IP地址
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void createVideoDetailNode() {
        try {
            // 创建 zookeeper 商品售罄信息根节点
            String path = ZkCacheConstant.VIDEO_DETAIL_PREFIX;
            if (zooKeeper != null && zooKeeper.exists(path, false) == null) {
                zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void createIntranetIpNode() {
        try {
            // 创建 zookeeper 商品售罄信息根节点
            String path = ZkCacheConstant.INTRANET_IP_PREFIX;
            if (zooKeeper != null && zooKeeper.exists(path, false) == null) {
                zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void refreshVideoDetailCache(String data, String path) {
        if (WatchTypeEnum.VIDEO_DETAIL.getType().equals(getCacheType(data))) {
            String liveNo = path.substring(path.lastIndexOf("/") + 1, path.length());
            JvmCache.videoMap.remove(liveNo);
        }
    }


    public void refreshIntranetIp(String data) {
        if (WatchTypeEnum.INTRANET_IP.getType().equals(getCacheType(data))) {
            JvmCache.ipList = new CopyOnWriteArrayList();
            redisTemplate.delete(RedisKeyConstant.LiveVideoResources.INTRANET_IP);
        }
    }


    /**
     * 构建参数
     *
     * @param data
     * @return
     */
    private String getCacheType(String data) {
        return Arrays.asList(data.split(ZkCacheConstant.SPLIT)).get(0);
    }


}
